package com.ship.dispatch.service.fob.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.SpArrangeSchemeDetail;
import com.ship.dispatch.bean.SpDispatchSchemeDetail;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
import com.ship.dispatch.bean.SpPortInformation;
import com.ship.dispatch.bean.fob.*;
import com.ship.dispatch.bean.orderPay.SpFundManage;
import com.ship.dispatch.bean.orderPay.SpPaymentOrder;
import com.ship.dispatch.bean.orderPay.SpPaymentOrderDetail;
import com.ship.dispatch.bo.orderPay.SpPaymentOrderBO;
import com.ship.dispatch.bo.orderPay.SpPaymentOrderDetailBO;
import com.ship.dispatch.bpm.service.ProcessInstanceService;
import com.ship.dispatch.bpm.service.TaskService;
import com.ship.dispatch.bpm.utils.CalculateDateUtil;
import com.ship.dispatch.bpm.utils.JsonUtils;
import com.ship.dispatch.bpm.utils.TemplateParamUtils;
import com.ship.dispatch.bpm.vo.ManageEntityVo;
import com.ship.dispatch.bpm.vo.dto.BpmTaskDto;
import com.ship.dispatch.mapper.SpArrangeSchemeDetailMapper;
import com.ship.dispatch.mapper.SpPortInformationMapper;
import com.ship.dispatch.mapper.fob.SpFobZfbxfyMapper;
import com.ship.dispatch.mapper.fob.SpFobZfdsfjlfyMapper;
import com.ship.dispatch.service.SpDispatchSchemeDetailService;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
import com.ship.dispatch.service.fob.*;
import com.ship.dispatch.service.orderPay.SpPaymentOrderService;
import com.ship.dispatch.util.WordUtil;
import com.ship.system.api.BpmInstanceService;
import com.ship.system.api.RemoteUserService;
import com.ship.system.api.domain.SysUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yl
 * @title SpFobZfbxfyServiceImpl
 * @description
 * @create 2023/12/19 0019
 */
@Service
public class SpFobZfbxfyServiceImpl extends FobBaseServiceImpl<SpFobZfbxfyMapper, SpFobZfbxfy> implements SpFobZfbxfyService {

    @Autowired(required = false)
    SpFobZfbxfyMapper mapperapper;

    @Autowired
    SpFobFileRecordService spFobFileRecordService;

    @Autowired
    SpDispatchSchemeExecuteService schemeDetailService;

    @Autowired
    SpFobTemplateService spFobTemplateService;

    @Autowired
    SpFobSyzlzzwjService spFobSyzlzzwjService;

    @Autowired(required = false)
    SpPortInformationMapper spPortInformationMapper;

    @Override
    public void updateEntity(ManageEntityVo manageEntityVo, String json) {
        SpFobZfbxfy object = JsonUtils.jsonToObject(json,SpFobZfbxfy.class);
        SpFobZfbxfy his = mapperapper.selectOne(new LambdaQueryWrapper<SpFobZfbxfy>().eq(SpFobZfbxfy::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobZfbxfy::getStatus,-2));
        if(manageEntityVo.getOperationType()==1) {
            object.setStatus(1);
        }
        if(his==null){ // 新增
            object.setSchemeDetailId(manageEntityVo.getSchemeDetailId());
            object.setTaskId(manageEntityVo.getTaskId());
            object.setProceeInstanceId(manageEntityVo.getProcessInstanceId());
            mapperapper.insert(object);
        }else { // 修改
            object.setId(his.getId());
            object.setOrderId(his.getOrderId());
            BeanUtils.copyProperties(object,his);
            /*if(his.getStatus()!=null && his.getStatus()==1 && his.getOrderId()==null){
                Long orderId = createPayOrder(manageEntityVo.getProcessInstanceId(),his);
                his.setOrderId(orderId);
            }*/
            mapperapper.updateById(his);
            // 处理多余文件记录
            List<String> ids = new ArrayList<>();
            his = mapperapper.selectOne(new LambdaQueryWrapper<SpFobZfbxfy>().eq(SpFobZfbxfy::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobZfbxfy::getStatus,-2));
            if((his.getFiels()!=null && his.getFiels().length()>0)){
                String temp = his.getFiels();
                String[] fieldIds = temp.split(",");
                ids =  Arrays.stream(fieldIds).collect(Collectors.toList());
            }
            if(his.getFieleTemplate()!=null){
                SpFobFileRecord record = spFobFileRecordService.selectByServiceAndTemplate(his.getId(),his.getFieleTemplate());
                if(record!=null){
                    ids.add(record.getId()+"");
                }
            }
            if(StringUtils.isNotEmpty(his.getBusniessFile())){
                String temp = his.getBusniessFile();
                String[] fieldIds = temp.split(",");
                List<String> templIds =  Arrays.stream(fieldIds).collect(Collectors.toList());
                ids.addAll(templIds);
            }
            spFobFileRecordService.deleteOtherFileRecor(his.getId(),ids);
        }
    }

    @Autowired
    SpFobGmbxService  spFobGmbxService;
    public void createPayOrder(Long id){
        SpFobZfbxfy his = this.getById(id);
        List<SpFobZfbxfy> otherList = this.list(new LambdaQueryWrapper<SpFobZfbxfy>().eq(SpFobZfbxfy::getProceeInstanceId,his.getProceeInstanceId()).eq(SpFobZfbxfy::getApprvalStatus,1));
        SpFobGmbx gmbx = spFobGmbxService.findData(his.getProceeInstanceId());
        for(SpFobZfbxfy his2:otherList){
            if(gmbx!=null && gmbx.getOrderId()!=null &&  his2.getOrderId()==null){
                Long orderId = createPayOrder(gmbx.getOrderId(),his2.getProceeInstanceId(),his2);
                his2.setOrderId(orderId);
                this.updateById(his2);
            }
        }
        /*if(gmbx!=null && gmbx.getOrderId()!=null && his.getOrderId()==null){
            Long orderId = createPayOrder(gmbx.getOrderId(),his.getProceeInstanceId(),his);
            his.setOrderId(orderId);
            this.updateById(his);
        }*/
    }

    @Override
    public SpFobBaseBean getBaseBeanByInstanceId(String id) {
        return mapperapper.selectOne(new LambdaQueryWrapper<SpFobZfbxfy>().eq(SpFobZfbxfy::getProceeInstanceId,id).ne(SpFobZfbxfy::getStatus,-2));
    }
    @Override
    public void  saveEntity(SpFobBaseBean bean){
        SpFobZfbxfy spFob = new SpFobZfbxfy();
        BeanUtils.copyProperties(bean,spFob);
        this.save(spFob);
    }

    @Override
    public void updateEntityById(SpFobBaseBean bean) {
        SpFobZfbxfy spFob = new SpFobZfbxfy();
        BeanUtils.copyProperties(bean,spFob);
        this.updateById(spFob);
    }


    @Override
    public Object getFormData(String id,Long serviceId) {
        SpFobZfbxfy spFobZzgcjr = null;
        if(serviceId!=null){
            spFobZzgcjr = mapperapper.selectById(serviceId);
        }else {
            spFobZzgcjr = mapperapper.selectOne(new LambdaQueryWrapper<SpFobZfbxfy>().eq(SpFobZfbxfy::getProceeInstanceId,id).ne(SpFobZfbxfy::getStatus,-2));
        }
        if(spFobZzgcjr==null){
            return null;
        }
        if(StringUtils.isEmpty(spFobZzgcjr.getCostUnit())){
            spFobZzgcjr.setCostUnit("2");
        }
        Map<String,Object> map = JsonUtils.jsonToMap(JsonUtils.objectToJson(spFobZzgcjr), Object.class);
        if(StringUtils.isNotBlank(spFobZzgcjr.getFiels())){
            String[] ids = spFobZzgcjr.getFiels().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("fiels",spFobFileRecordList);
        }
        if(spFobZzgcjr.getBusniessFile()!=null){
            String[] ids = spFobZzgcjr.getBusniessFile().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("busniessFile",spFobFileRecordList);
        }
        if(spFobZzgcjr.getFieleTemplate()!=null){
            SpFobFileRecord record = spFobFileRecordService.selectByServiceAndTemplate(spFobZzgcjr.getId(),spFobZzgcjr.getFieleTemplate());
            if(record!=null){
                map.put("filePath",record.getPath());
            }
        }else{
            map.put("filePath","");
        }
        SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(spFobZzgcjr.getProceeInstanceId());
        if (execute.getExpectedLoadingPort()!=null && spFobZzgcjr.getPort() == null){
            map.put("port",execute.getExpectedLoadingPort());
        }
        map.put("approvalStatus",spFobZzgcjr.getApprvalStatus());
        return map;
    }
    @Override
    public String  getTemplateParam(ManageEntityVo manageEntityVo) {
        ObjectNode json = manageEntityVo.getData();
        SpFobZfbxfy spFobZzgcjr = JsonUtils.jsonToObject(JsonUtils.objectToJson(json),SpFobZfbxfy.class);
        String templateId = spFobZzgcjr.getTemplateId();
        if(templateId==null){
            throw  new BusException("请选模板后再生成模板正文", BaseResultCode.GENERAL_ERROR);
        }
        SpFobTemplate spFobTemplate = spFobTemplateService.getById(templateId);
        if(spFobTemplate == null){
            throw  new BusException("当前模板不存在，请联系管理员处理", BaseResultCode.GENERAL_ERROR);
        }
        // 调度方案信息
        SpDispatchSchemeExecute schemeDetail = schemeDetailService.getExceuteByInstanceId(manageEntityVo.getProcessInstanceId());
        Map<String,String> map = new HashMap<>();
        if(schemeDetail!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(schemeDetail),String.class);
            for(String key:tempMap.keySet()){
                map.put("spDispatchSchemeDetail."+key,tempMap.get(key));
            }
        }
        List<SpFobSyzlzzwj> spFobSyzlzzwjs = spFobSyzlzzwjService.list(new LambdaQueryWrapper<SpFobSyzlzzwj>().eq(SpFobSyzlzzwj::getProceeInstanceId,manageEntityVo.getProcessInstanceId()));
        if(spFobSyzlzzwjs.size()>0){
            map.put("temp1",CalculateDateUtil.pasrseDate(spFobSyzlzzwjs.get(0).getOnLoadDate()));
        }
        SpPortInformation spPortInformation = null;
        if(schemeDetail.getExpectedUnloadingPort()!=null){
            spPortInformation = spPortInformationMapper.selectOne(new LambdaQueryWrapper<SpPortInformation>()
                    .eq(SpPortInformation::getPortNameEnglish,schemeDetail.getExpectedLoadingPort())
                    .or().eq(SpPortInformation::getPortNameChinese,schemeDetail.getExpectedLoadingPort())
                    .last("LIMIT 1")
            );
        }
        if(spPortInformation!=null){
            map.put("temp2",spPortInformation.getPortCountry());
        }else {
            map.put("temp2","");
        }
        // 当前业务表单信息
        if(json!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(json),String.class);
            for(String key:tempMap.keySet()){
                map.put("spFobZfbxfy."+key,tempMap.get(key));
            }
        }
        String template = "";
        if(spFobTemplate !=null){
            template = TemplateParamUtils.processDynamicParams(spFobTemplate.getContent(),map);
        }
        return template;
    }

    @Override
    public List<Long> findServieData(String processInstanceId){
        List<SpFobZfbxfy> spFobBaseBeans =  mapperapper.selectList(new LambdaQueryWrapper<SpFobZfbxfy>().eq(SpFobZfbxfy::getProceeInstanceId,processInstanceId).orderByDesc(SpFobZfbxfy::getCreateDate));
        List<Long> list = spFobBaseBeans.stream().map(SpFobBaseBean::getId).collect(Collectors.toList());
        return list;
    }
    @Autowired
    SpFobQrxzgService spFobQrxzgService;
    @Autowired
    SpFobSyzlxzwjService spFobSyzlxzwjService;

    @Autowired
    SpPaymentOrderService spPaymentOrderService;

    @Autowired(required = false)
    SpArrangeSchemeDetailMapper spArrangeSchemeDetailMapper;
    /**
     * 创建支付订单
     * @param processInstanceId
     * @param his
     */
    public Long createPayOrder(Long oldId,String processInstanceId,SpFobZfbxfy his){
        SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(processInstanceId);
        SpPaymentOrderBO spPaymentOrderBO = new SpPaymentOrderBO();
        //卸载港船代尾款
        spPaymentOrderBO.setOrderType(6);
        //contractType  船舶代理
        //spPaymentOrderBO.setContractType();
        spPaymentOrderBO.setPayAmount(his.getCostAmount());
        spPaymentOrderBO.setPayEndTime(his.getPlanEndDate());
        spPaymentOrderBO.setVoyageNo(execute.getVoyageNo());
        if(his.getCostUnit()!=null && his.getCostUnit()!=""){
            spPaymentOrderBO.setPayAmountUnit(Integer.parseInt(his.getCostUnit()));
        }else{
            spPaymentOrderBO.setPayAmountUnit(2);
        }
        //spPaymentOrderBO.setPayAmountUnit(Integer.parseInt(his.getCostUnit()));
        spPaymentOrderBO.setOrderStatus(3);
        spPaymentOrderBO.setId(oldId);
        List<BpmTaskDto> tasks = taskService.findActivitiOrFinishTaskResult(his.getOrderProcessId());
        // 封装用户信息
        if(tasks.size()>=2){
            SysUser user = remoteUserService.getUserByName(tasks.get(0).getAssigneeId());
            if(user!=null){
                spPaymentOrderBO.setHandlePeople(user.getUserName());
            }
            SysUser user2 = remoteUserService.getUserByName(tasks.get(1).getAssigneeId());
            if(user2!=null){
                spPaymentOrderBO.setApprovedPeople(user2.getUserName());
            }
        }else if(tasks.size()>=1){
            SysUser user = remoteUserService.getUserByName(tasks.get(0).getAssigneeId());
            if(user!=null){
                spPaymentOrderBO.setHandlePeople(user.getUserName());
                spPaymentOrderBO.setApprovedPeople(user.getUserName());
            }
        }
        SpPaymentOrder order = spPaymentOrderService.synchronousPayOrder(spPaymentOrderBO);

        //对于订单明细
        SpPaymentOrderDetailBO spPaymentOrderDetailBO = new SpPaymentOrderDetailBO();
        spPaymentOrderDetailBO.setOrderId(order.getId());
        spPaymentOrderDetailBO.setPayableAmount(his.getCostAmount());
        //Map<String, String> tempMap = spFobZzcbdlService.findConShippingAgency(zzcbdls.get(0).getCronId());
        if("1".equals(execute.getTradeBody())){
            spPaymentOrderDetailBO.setCnoocCorporation("CNOOC Gas and Power Trading& Marketing Limited");
        }else {
            spPaymentOrderDetailBO.setCnoocCorporation("CNOOC Gas and Power Singapore Trading& Marketing Pte. Ltd");
        }
        spPaymentOrderDetailBO.setShipName(execute.getShipName());
        spPaymentOrderDetailBO.setExpectedLoadingPort(execute.getExpectedLoadingPort());
        spPaymentOrderDetailBO.setExpectedLoadingDate(execute.getExpectedLoadingDate());
        spPaymentOrderDetailBO.setExpectedUnloadingDate(execute.getExpectedUnloadingWindow());
        spPaymentOrderDetailBO.setExpectedUnloadingPort(execute.getExpectedUnloadingPort());
        //实际保单
        spPaymentOrderDetailBO.setActualPolicyInfo("1");
        if(execute.getRealityLoadingDate()!=null){
            spPaymentOrderDetailBO.setRealityLoadingDate(execute.getRealityLoadingDate());
        }
        SpArrangeSchemeDetail arrangeSchemeDetail = spArrangeSchemeDetailMapper.selectById(execute.getArrangeSchemeDetailId());
        if(arrangeSchemeDetail!=null){
            spPaymentOrderDetailBO.setEstimateLoadVolume(arrangeSchemeDetail.getLoadingCapacity());
        }
        spPaymentOrderDetailBO.setPayableAmount(his.getCostAmount());
        //设置投保额度
        spPaymentOrderDetailBO.setSumInsure(his.getCostAmount());
        spPaymentOrderService.synchronousPayOrderDetail(spPaymentOrderDetailBO);
        return order.getId();
    }


    @Resource
    @Lazy
    ProcessInstanceService processInstanceService;
    @Override
    public void startPostInstance(Long businessId,String key){
        SpFobZfbxfy spFobZfzzcdyfk = this.getById(businessId);
        if(spFobZfzzcdyfk.getOrderProcessId()!=null && (spFobZfzzcdyfk.getApprvalStatus()==0 || spFobZfzzcdyfk.getApprvalStatus()==1)){
            throw new BusException("当前已发起审批，不可重复发起",BaseResultCode.GENERAL_ERROR);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("serviceType",key);
        map.put("moduleName","船运执行");
        map.put("reason","");
        String result = processInstanceService.createProcessInstance2(BpmInstanceService.SP_PAY_ORDER_EXISTS_BPM_KEY,map,businessId+"");
        spFobZfzzcdyfk.setOrderProcessId(result);
        spFobZfzzcdyfk.setApprvalStatus(0);
        spFobZfzzcdyfk.setCreateBy(SecurityUtils.getUsername());
        this.updateById(spFobZfzzcdyfk);
    }

    @Override
    public boolean checkApproveStatus(Long businessId) {
        SpFobZfbxfy spFobZfzzcdyfk = this.getById(businessId);
        if(spFobZfzzcdyfk.getApprvalStatus()!=null && spFobZfzzcdyfk.getApprvalStatus()==1){
            return true;
        }
        return false;
    }

    @Resource
    @Lazy
    TaskService taskService;

    @Resource
    @Lazy
    RemoteUserService remoteUserService;

    @Resource
    WordUtil wordUtil;
    @Override
    @Transactional
    public void updateApprovaResult(Long businessId,Integer status){
        SpFobZfbxfy spFobZfzzcdyfk = this.getById(businessId);
        if(status==1 && (StringUtils.isNotEmpty(spFobZfzzcdyfk.getFieleTemplate()) || StringUtils.isNotEmpty(spFobZfzzcdyfk.getBusniessFile()))){ // 处理业务说明文件不为空，更新业务文件
            List<BpmTaskDto> tasks = taskService.findActivitiOrFinishTaskResult(spFobZfzzcdyfk.getOrderProcessId());
            Map<String, SysUser> map = new HashMap<>();
            // 封装用户信息
            if(tasks.size()>=1){
                SysUser user = remoteUserService.getUserByName(tasks.get(0).getAssigneeId());
                user.setCreateTime(tasks.get(0).getFinishTime());
                map.put("业务部门负责人：",user);
                String userName = "";
                if(tasks.size()>1){
                    userName = tasks.get(1).getAssigneeId();
                    if(userName==null) userName = SecurityUtils.getUsername();
                    SysUser user2 = remoteUserService.getUserByName(userName);
                    user2.setCreateTime(tasks.get(1).getFinishTime());
                    map.put("业务审核人：",user2);
                }else{
                    SysUser user2 = new SysUser();
                    BeanUtils.copyProperties(user,user2);
                    //user2.setCreateTime(tasks.get(0).getFinishTime());
                    map.put("业务审核人：",user2);
                }
                SysUser user3 = remoteUserService.getUserByName(spFobZfzzcdyfk.getCreateBy());
                user3.setCreateTime(spFobZfzzcdyfk.getCreateDate());
                map.put("业务经办人：",user3);
            }
            if(!map.isEmpty()){
                wordUtil.updateFileTemplate(businessId,spFobZfzzcdyfk.getFieleTemplate(),map,spFobZfzzcdyfk.getBusniessFile());
            }
        }
        //记录状态
        spFobZfzzcdyfk.setApprvalStatus(status);
        this.updateById(spFobZfzzcdyfk);
    }


}
